<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    fullscreen
    destroyOnClose
    @ok="handleOk"
    :ok-button-props="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="disableSubmit">
        <a-form :form="form" slot="detail" >
          <a-list>
            <a-list-item>
              <a-row style="width: 100%;">
                <a-col :span="24">
                  <a-row :gutter="gutter" style="width: 100%;">
                    <a-col :span="12" v-for="(item,index) in itemList" :key="index">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="{span:6}"
                        :wrapperCol="{span:18}"
                        :label="item.columnDesc">
                        <j-multi-select-tag v-if="item.columnName==='labels'" v-decorator="['labels']" :trigger-change="true" dictCode="subject_labels" placeholder="请选择标签" />
                        <j-image-upload isMultiple v-else-if="item.columnName==='imgs'" :placeholder="'请输入'+item.columnDesc" v-decorator="[item.columnName,{rules: [{required: item.notNull, message: '请输入'+item.columnDesc+'!'}]}]" ></j-image-upload>
                        <a-input readOnly v-else-if="isRegionInput(item.columnName)" :placeholder="'请在地图上选择'+item.columnDesc" v-decorator="[item.columnName,{rules: [{required: item.notNull, message: '请输入'+item.columnDesc+'!'}]}]"/>
                        <a-input v-else :placeholder="'请输入'+item.columnDesc" v-decorator="[item.columnName,{rules: [{required: item.notNull, message: '请输入'+item.columnDesc+'!'}]}]"/>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
            </a-list-item>
          </a-list>
        </a-form>
        <div class="map">
          <MapBaseYt ref="mapBaseYt" :initZoom=8 @loaded="initMap" />
        </div>
        <!-- <map-modal ref="mapModal" @mapOk="mapOk"/> -->
        <!-- <div id="map" class="map"></div> -->
      </j-form-container>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
// import MapModal from './MapModal'
import MapBaseYt from '@comp/map/MapBaseYt'
import tempIcon from '@assets/map/icon/icon-temp.png'
import pick from 'lodash.pick'
export default {
  name: 'ResourcesModel',
  // components: { MapModal },
  components: { MapBaseYt },
  data() {
    return {
      width: 1200,
      departTree: [],
      orgTypeData: [],
      phoneWarning: '',
      departName: '',
      markerLayerGroup: null,
      title: '操作',
      gutter: 8,
      itemList: [],
      seen: false,
      visible: false,
      condition: true,
      layerDetail: {},
      disableSubmit: false,
      showFields: [],
      model: {},
      threeCol: {
        label: { span: 6 },
        wrapper: { span: 24 - 6 }
      },
      menuhidden: false,
      menuusing: true,
      lat: null,
      lng: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 行政区划相关数据，点击经纬度后，请求接口，获取行政区划字段
      areaCode: null,
      areaName: null,
      streetName: null,
      streetCode: null,
      communityName: null,
      communityCode: null,

      map: null,
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        add: '/subject/scSubjectLayerInfo/layerDataAdd/',
        edit: '/subject/scSubjectLayerInfo/layerDataEdit/',
        getRegion: '/gisWms/getRegion'// 获取行政数据
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    add(layerDetail) {
      this.edit({}, layerDetail)
    },
    edit(record, layerDetail) {
      this.layerDetail = layerDetail
      this.itemList = this.layerDetail.layerDetails
      this.form.resetFields()
      for (const item of this.itemList) {
        this.showFields.push(item.columnName)
      }
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, ...this.showFields))
      })
      this.lat = record.lat
      this.lng = record.lng
      if (this.map && this.lat && this.lng) {
        this.markerLayerGroup.clearLayers()
        this.markerLayerGroup.addLayer(this.showLayer(this.lat, this.lng))
      }
    },
    // 判断是否是行政区划或者经纬度，如果是，则不能编辑
    isRegionInput(columnName) {
      return columnName === 'lat' ||
      columnName === 'lng' ||
      columnName === 'area_name' ||
      columnName === 'area_code' ||
      columnName === 'street_name' ||
      columnName === 'street_code' ||
      columnName === 'community_code' ||
      columnName === 'community_name'
    },
    close() {
      this.disableSubmit = false
      this.visible = false
      this.showFields = []
      // if (this.map) { this.map.remove() }
      // this.map = null
      this.lat = null
      this.lng = null
      this.$emit('close')
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          const formData = Object.assign({}, values)

          let url = this.url.add + this.layerDetail.id
          if (this.model.id) {
            url = this.url.edit + this.layerDetail.id
          }
          console.log('创建数据：', formData)
          postAction(url, formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    // 根据地图选择的经纬度，获取行政区划数据，并且数据展示在页面上
    getRegion() {
      var that = this
      that.confirmLoading = true
      getAction(this.url.getRegion, { longitude: this.lng, latitude: this.lat }).then((res) => {
        if (res.success) {
          var data = res.result
          that.model.area_name = data.areaName
          that.model.area_code = data.areaCode
          that.model.street_name = data.streetName
          that.model.street_code = data.streetCode
          that.model.community_code = data.communityCode
          that.model.community_name = data.communityName
          that.model.lat = that.lat
          that.model.lng = that.lng
          that.$nextTick(() => {
            that.form.setFieldsValue(pick(that.model, ...this.showFields))
          })
          that.markerLayerGroup.clearLayers()
          that.markerLayerGroup.addLayer(that.showLayer(that.lat, that.lng))
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
        // that.close()
      })
    },
    // 初始化地图
    initMap() {
      this.map = this.$refs.mapBaseYt.map
      this.markerLayerGroup = L.layerGroup().setZIndex(1)
      this.map.addLayer(this.markerLayerGroup)
      if (this.lat && this.lng) {
        this.markerLayerGroup.clearLayers()
        this.markerLayerGroup.addLayer(this.showLayer(this.lat, this.lng))
      }
      if (!this.disableSubmit) {
        var that = this
        this.map.on('click', function(e) {
          var lat = e.latlng.lat
          var lng = e.latlng.lng
          that.lat = lat
          that.lng = lng
          that.getRegion()
        })
      }
    },
    showLayer(lat, lng) {
      var marker = L.marker([lat, lng], {
        icon: L.icon({
          iconUrl: tempIcon,
          iconSize: [30, 30],
          iconAnchor: [20, 20]
        })
      })
      return marker
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>
.left{
  width: 50%;
  height: 100%;
  float: left;
  background-color: aquamarine;
}
.map{
  background-color: #0079fe;
  width: 100%;
  height: 500px;
}
.searchDiv {
    display: flex;
    align-items: center;
    height: 8%;

    /* p {
        margin-left: 10px;
    } */
}
#allmap {
    height: 92%;
}
.searchValue {
    width: 200px;
    vertical-align: bottom;
}
.myBtn {
    margin-left: 16px;
    height: 30px;
    /*line-height: 30px;*/
    width: 60px;
    background-color: #0079fe;
    /*text-align: center;*/
    color: #fff;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.cancelBtn {
    background-color: #ececec;
    color: #6a6a6a;
}
.mapBtn {
    margin-bottom: 60px;
    color: rgb(213 34 21);
    text-decoration: underline;
    cursor: pointer;
    box-sizing: border-box;
    padding: 0 30%;
}
</style>
